package com.zy.edu.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.zy.edu.bean.*;
import com.zy.edu.config.SystemParam;
import com.zy.edu.dao.CourseChapterClassDao;
import com.zy.edu.service.CourseChapterClassService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.zy.edu.service.CourseChapterService;
import com.zy.edu.service.CourseService;
import com.zy.edu.service.UserService;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author HuangHaiShui
 * @since 2021-07-27
 */
@Service
@Transactional
public class CourseChapterClassServiceImpl extends ServiceImpl<CourseChapterClassDao, CourseChapterClass> implements CourseChapterClassService {

    @Resource
    CourseChapterService courseChapterService;
    @Resource
    CourseService courseService;
    @Resource
    UserService userService;
    @Override
    public Map associatedCourse(InputParam inputParam) throws Exception {
        //为班级关联课程  课程列表为多个
        if(StringUtils.isEmpty(inputParam.getClassId())
                || StringUtils.isEmpty(inputParam.getCourseIds()) ) {
            return ResponseInfo.error(SystemParam.ERROR_PARAMS);
        }else{
            //前端传递进来的课程
            String[] idArr = inputParam.getCourseIds().split(",");
            //已有的课程
            String[] courseIds = getCourseIdsByClassId(inputParam.getClassId());

            //要取消关联的课程
            List<String> delList = compare(idArr,courseIds);
            for (String s : delList) {
                deleCourse(inputParam.getClassId(),s);
            }
            //要新增关联的课程
            List<String> addList = compare(courseIds,idArr);
            for (String s : addList) {
                addCourse(inputParam.getClassId(),s);
            }

            return ResponseInfo.success("关联成功");
        }
    }

    //获取该班级目前已关联的所有课程
    private String[] getCourseIdsByClassId(String classId){
        EntityWrapper<CourseChapterClass> entityWrapper = new EntityWrapper<>();
        entityWrapper.setSqlSelect("course_id as courseId");
        entityWrapper.eq("class_id",classId);
        entityWrapper.groupBy("course_id");
        List<CourseChapterClass> list = this.baseMapper.selectList(entityWrapper);
        String[] res = new String[list.size()];
        if(list.size()>0) {
            for (int i = 0; i < list.size(); i++) {
                res[i] = list.get(i).getCourseId();
            }
        }
        return res;
    }

    private static <T> List<T> compare(T[] t1, T[] t2) {
        //将t1数组转成list数组
        List<T> list1 = Arrays.asList(t1);
        //用来存放2个数组中不相同的元素
        List<T> list2 = new ArrayList<T>();
        for (T t : t2) {
            if (!list1.contains(t)) {
                list2.add(t);
            }
        }
        return list2;
    }

    @Override
    public Map getCourseByClassId(InputParam inputParam) {

        if(StringUtils.isEmpty(inputParam.getClassId()) ) {
            return ResponseInfo.error(SystemParam.ERROR_PARAMS);
        }else{
            String[] ids = getCourseIdsByClassId(inputParam.getClassId());
            return ResponseInfo.success(ids);
        }
    }

    @Override
    public List<CourseChapterClass> findClassIdsByCourseId(InputParam inputParam) {
        return this.baseMapper.findClassIdsByCourseId(inputParam);
    }

    @Override
    public Integer getCountByParam(String classId) {
        EntityWrapper<CourseChapterClass> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("class_id",classId);
        entityWrapper.eq("status",1);//已上过
        Integer count = this.baseMapper.selectCount(entityWrapper);
        return count;
    }

    //删除关联
    private void deleCourse(String classId,String courseId){
        EntityWrapper<CourseChapterClass> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("course_id",courseId);
        entityWrapper.eq("class_id",classId);
        this.delete(entityWrapper);
    }

    //创建关联
    private void addCourse(String classId,String courseId) throws Exception {
        //查询出该课程的所有课时，添加相关记录
        EntityWrapper<CourseChapter> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("course_id",courseId);
        entityWrapper.eq("status",1);
        entityWrapper.orderBy("num",true);
        List<CourseChapter> courseChapters = courseChapterService.selectList(entityWrapper);
        List<CourseChapterClass> res = new ArrayList<>();
        for (CourseChapter courseChapter : courseChapters) {
            CourseChapterClass ccc = new CourseChapterClass();
            ccc.setId(UUID.randomUUID().toString().replaceAll("-", ""));
            ccc.setChapterId(courseChapter.getId());
            ccc.setClassId(classId);
            ccc.setCourseId(courseId);
            ccc.setStatus(0);//未上课
            ccc.setCreateTime(new Date());
            res.add(ccc);
        }
        if(res.size()>0) {
            this.insertBatch(res);
        }else{
            throw new Exception("所选课程无课时，不可关联");
        }
    }


    @Override
    public Map updateStatus(CourseChapterClass courseChapterClass, InputParam inputParam) {

        if(StringUtils.isEmpty(courseChapterClass.getId())){
            return ResponseInfo.error(SystemParam.ERROR_PARAMS);
        }else{
            courseChapterClass.setStatus(1);//修改为上课状态
            this.updateById(courseChapterClass);
        }
        return ResponseInfo.success("修改成功");
    }

    @Override
    public Map getByClassAndCourse(InputParam inputParam) {
        if(StringUtils.isEmpty(inputParam.getClassId())
            ||StringUtils.isEmpty(inputParam.getCourseId())){
            return ResponseInfo.error(SystemParam.ERROR_PARAMS);
        }else {
            //老师登录后的主页取数据流程
            User temp = userService.selectById(inputParam.getUserId());
            if(temp.getRoleType().equals(Role.STUDENT)){
                return  courseService.findAllByStuId(inputParam);
            }else {
                return ResponseInfo.success(
                        this.baseMapper.getByClassAndCourse(inputParam));
            }
        }
    }


}
